package mwa.cs.sm.ctrl;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import mwa.cs.dao.CommentDAO;
import mwa.cs.dao.RequestTypeDAO;
import mwa.cs.dao.SMErrorLogDAO;
import mwa.cs.database.Database;
import mwa.cs.model.Comment;
import mwa.cs.model.RequestType;
import mwa.cs.util.JDate;

public class CS11009Srvl extends HttpServlet {

	private Database db;
	private int vnSiteId;
	private int vnUserId;
	private String vaUrlAddress;
	private String vaAgentBrowser;

	public CS11009Srvl() {
		super();

	}

	public void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		vnSiteId = Integer.parseInt(request.getSession().getAttribute("site_id").toString());
		vnUserId = Integer.parseInt(request.getSession().getAttribute("user_id").toString());
    	vaUrlAddress = request.getParameter("url_address");
    	vaAgentBrowser = request.getParameter("agent_browser");
		String vaProcessType = request.getParameter("process_type");

		if (vaProcessType.equals("insert")) {
			insert(request, response);
		} else if (vaProcessType.equals("edit")) {
			edit(request, response);
		} else if (vaProcessType.equals("delete")) {
			delete(request, response);
		} else if (vaProcessType.equals("update")) {
			update(request, response);
		} else {
			getDataTable(request, response);
		}
	}

	private void getDataTable(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/JSON");
		JSONObject voObject = new JSONObject();
		JSONArray voRow = new JSONArray();
		JSONArray voColumn = null;
		PrintWriter voOut = response.getWriter();

		this.db = new Database();
		RequestTypeDAO voRequestTypeDAO = new RequestTypeDAO(db);
		List<Map<String, Object>> voListFindAll;
		voListFindAll = voRequestTypeDAO.findRequestType(vnSiteId);

		for (int i = 0; i < voListFindAll.size(); i++) {
			Map<String, Object> voMapItem = (Map<String, Object>) voListFindAll
					.get(i);
			voColumn = new JSONArray();
			voColumn.add(i + 1);

			if (voMapItem.get("REQUEST_GROUP") == null)
				voColumn.add("");
			else if (voMapItem.get("REQUEST_GROUP").toString().trim().equals("0")
					|| voMapItem.get("REQUEST_GROUP").toString().trim()
							.equals("1"))
				voColumn.add(voMapItem.get("REQUEST_GROUP").toString().trim()
						.equals("0") ? "เกี่ยวกับมาตร" : "ไม่เกี่ยวกับมาตร");
			else
				voColumn.add("");

			voColumn.add(voMapItem.get("REQUEST_TYPE") == null ? "" : voMapItem
					.get("REQUEST_TYPE").toString());
			voColumn.add(voMapItem.get("REQUEST_DESCRIPTION") == null ? ""
					: voMapItem.get("REQUEST_DESCRIPTION").toString());
			voRow.add(voColumn);
		}

		voObject.put("iTotalRecords", voListFindAll.size());
		voObject.put("iTotalDisplayRecords", voListFindAll.size());
		voObject.put("aaData", voRow);
		
		db.close();

		voOut.print(voObject.toJSONString());

	}

	public void insert(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/JSON");
		this.db = new Database();
		String vaDate = JDate.getDate();
		String vaTime = JDate.getTime();

		String vaRequestGroup = request.getParameter("REQUEST_GROUP").toString();
		String vaRequestType = request.getParameter("REQUEST_TYPE").toString();
		String vaRequestDescription = request
				.getParameter("REQUEST_DESCRIPTION").toString();

		RequestTypeDAO voRequestDAO = new RequestTypeDAO(db);
		List<Map<String, Object>> voCheckCodeId = voRequestDAO
				.findRequestTypeByCondition(vnSiteId, " REQUEST_TYPE = '"
						+ vaRequestType + "'");

		if (voCheckCodeId == null || voCheckCodeId.size() == 0) {
			// / Can save, no duplicate
			RequestType voReq = new RequestType(vnSiteId, vaRequestGroup,
					vaRequestType, vaRequestDescription, vnUserId, vaDate, vaRequestDescription,
					vnUserId, vaDate, vaRequestDescription);
			try {
				db.beginTransaction();
				voRequestDAO.addRequestType(voReq);
				db.commit();
			} catch (Exception e) {
				SMErrorLogDAO.getInstance().addLog(0, "CS11009", JDate.getDate(), JDate.getTime(),vnUserId, "CS11009Srvl", e.getMessage(),vaUrlAddress, vaAgentBrowser);
				db.rollback();
				e.getMessage();
			}
			db.close();
			
			response.getWriter().write("success");

		} else {
			// Duplicate
			db.close();
			response.getWriter().write("CodeID_Dupicate");
		}
	}

	public void edit(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/JSON");
		this.db = new Database();
		String vaCodeId = request.getParameter("id");

		RequestTypeDAO voRequestTypeDAO = new RequestTypeDAO(db);

		List<Map<String, Object>> voObj = voRequestTypeDAO
				.findRequestTypeByCondition(vnSiteId, " request_type = '"
						+ vaCodeId + "'");
		
		db.close();

		if (voObj != null && voObj.size() > 0) {
			Map<String, Object> mObj = voObj.get(0);

			String vaGroup = mObj.get("REQUEST_GROUP").toString();
			String vaDesc = mObj.get("REQUEST_DESCRIPTION").toString();

			JSONObject voObject = new JSONObject();

			voObject.put("id", vaCodeId);
			voObject.put("group", vaGroup);
			voObject.put("desp", vaDesc);

			PrintWriter voOut = response.getWriter();
			voOut.print(voObject.toJSONString());

		} else {
			JSONObject voObject = new JSONObject();
			PrintWriter voOut = response.getWriter();
			voOut.print(voObject.toJSONString());
		}

	}

	public void update(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/JSON");
		this.db = new Database();
		String vaDate = JDate.getDate();
		String vaTime = JDate.getTime();

		String vaCodeId = request.getParameter("id");
		String vaDesp = request.getParameter("desp");
		String vaGroup = request.getParameter("group");
		String vaOldCodeId = request.getParameter("oldCodeID");

		RequestTypeDAO voRequestDAO = new RequestTypeDAO(db);

		// เช็คว่า Request_type ใหม่ มีซ้ำใน DB หรือยัง
		List<Map<String, Object>> voCheckCodeId = voRequestDAO
				.findRequestTypeByCondition(vnSiteId, " REQUEST_TYPE = '"
						+ vaCodeId + "'");

		// เช็คว่า Request_type อันเก่ามีใน DB หรือไม่
		List<Map<String, Object>> voCheckCodeIdOld = voRequestDAO
				.findRequestTypeByCondition(vnSiteId, " REQUEST_TYPE = '"
						+ vaOldCodeId + "'");

		if (voCheckCodeIdOld == null || voCheckCodeIdOld.size() == 0) {
			// Request_type ในระบบถูกลบไปแล้ว
			response.getWriter().write("CodeID_Error");
		}  else {
			// / Can update
			try {
				RequestType voReqType = new RequestType();
				voReqType.setVnSiteId(vnSiteId);
				voReqType.setVaRequestGroup(vaGroup);
				voReqType.setVaRequestType(vaCodeId);
				voReqType.setVaRequestDescription(vaDesp);

				voReqType.setVnInsertUserId(vnUserId);
				voReqType.setVaInsertDate(vaDate);
				voReqType.setVaInsertTime(vaTime);

				voReqType.setVnUpdateUserId(vnUserId);
				voReqType.setVaUpdateDate(vaDate);
				voReqType.setVaUpdateTime(vaTime);

				int vnRows  = 0;
				try {
					 db.beginTransaction();
					 vnRows = voRequestDAO.update(voReqType, vaOldCodeId);
					 db.commit();
				} catch (Exception e) {
					SMErrorLogDAO.getInstance().addLog(0, "CS11009", JDate.getDate(), JDate.getTime(),vnUserId, "CS11009Srvl", e.getMessage(),vaUrlAddress, vaAgentBrowser);
					db.rollback();
					e.getMessage();
				}

				if (vnRows > 0)
					response.getWriter().write("success");
				else
					response.getWriter().write("CodeID_Error");

			} catch (Exception ex) {
				SMErrorLogDAO.getInstance().addLog(0, "CS11009", JDate.getDate(), JDate.getTime(),vnUserId, "CS11009Srvl", ex.getMessage(),vaUrlAddress, vaAgentBrowser);
				
				response.getWriter().write("CodeID_Error");
			}finally{
				db.close();
			}
		}
	}

	public void delete(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/JSON");
		this.db = new Database();
		String vaCodeId = request.getParameter("id");

		RequestTypeDAO voReqTypeDAO = new RequestTypeDAO(db);
		boolean vbSuccess = false;
		try {
			db.beginTransaction();
			vbSuccess = voReqTypeDAO.delete(vnSiteId, vaCodeId);
			db.commit();
		} catch (Exception e) {
			SMErrorLogDAO.getInstance().addLog(0, "CS11009", JDate.getDate(), JDate.getTime(),vnUserId, "CS11009Srvl", e.getMessage(),vaUrlAddress, vaAgentBrowser);
			db.rollback();
			e.getMessage();
		}

		db.close();
		
		if (vbSuccess)
			response.getWriter().write("delete_sucess");
		else
			response.getWriter().write("delete_fail");
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

}
